package com.fau.wmbj.server.controller.current;

import cn.hutool.core.io.FileUtil;
import com.fau.wmbj.server.config.CurrentUser;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.idempotent.annotation.RepeatSubmit;
import com.fau.wmbj.server.service.UserService;
import com.fau.wmbj.server.storage.StorageService;
import com.fau.wmbj.server.utils.Message;
import com.fau.wmbj.server.utils.MimeTypeUtils;
import com.fau.wmbj.server.utils.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 当前用户
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-02-28 14:06
 */
@RestController
@RequestMapping("/current")
public class CurrentController {

    @Resource
    private UserService userService;
    @Resource
    private StorageService storageService;

    @GetMapping("/info")
    @ResponseBody
    public Message info(@CurrentUser User current) {
        return Message.success(userService.getCurrentUser());
    }

    @RepeatSubmit(interval = 1000)
    @RequestMapping("/update")
    @ResponseBody
    public Message getUserList(@RequestBody User userinfo, @CurrentUser User current) {
        if (!userinfo.getId().equals(current.getId())) {
            return Message.error("只能修改自己的信息");
        }
        User user = userService.find(current.getId());
        user.setNickName(userinfo.getNickName());
        user.setPhoneNumber(userinfo.getPhoneNumber());
        user.setEmail(userinfo.getEmail());
        user.setAvatar(userinfo.getAvatar());
        userService.update(user);
        return Message.success(user);
    }

    /**
     * 头像上传
     */
    @RepeatSubmit
    @PostMapping(value = "/upload-avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Message uploadAvatar(@RequestPart("file") MultipartFile file, @CurrentUser User user) {
        if (!file.isEmpty()) {
            String extension = FileUtil.extName(file.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return Message.error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            try {
                String avatar = storageService.upload(file);
                return Message.success("上传成功", avatar);
            } catch (Exception e) {
                e.printStackTrace();
                return Message.error(e.getMessage());
            }
        }
        return Message.error("上传图片异常，请联系管理员");
    }


}
